const Koa = require('koa');
const app = new Koa();
const request = require('superagent')
const bodyparser = require('koa-bodyparser');

let AppID = 'wx92381c5ccde47f67';
let AppSecret = '76826a139dc4e9f4894010061c0a15d3';
let access_token = 'xxxxx'
let openid = 'xxxxx'

// 引入koa-router并对其实例化
const router = require('koa-router')()

// 配置get路由
router.get('/get', function (ctx, next) {
  ctx.body = 'this is a get response!'
})
// 配置post路由
router.post('/post', function (ctx, next) {
  console.log(ctx.request.body);
  ctx.body = 'this is a post response!'
})

router.post('/wechatLogin', async (ctx, next) => {
  console.log(ctx.request.body);

  let res = await request
    .get(
      `https://api.weixin.qq.com/sns/jscode2session?appid=${AppID}&secret=${AppSecret}&js_code=${ctx.request.body.code}&grant_type=authorization_code`,
    )
    .type('json')
    .accept('json');
  console.log(res.text);
  let response = JSON.parse(res.text)
  openid = response.openid
  ctx.body = response;
})

// 点击发生订阅消息
router.post('/wechatPublishMessage', async (ctx, next) => {
  console.log(ctx.request.body)
  let requestData = {
    touser: ctx.request.body.openid,
    template_id: 'ZlnfWbwxLKHeyVaC6s7TlRszZKNe7VD7OaYXwX8-g0A',
    data: {
      thing7: {
        value: '已签到',
      },
      time4: {
        value: '2019年10月1日 15:01',
      },
      thing1: {
        value: '湖北武汉',
      },
      thing21: {
        value: '关山大道',
      },
      thing9: {
        value: '中午好',
      },
    },
  };

  let token = await request.get(
    `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${AppID}&secret=${AppSecret}`,
  );

  token = JSON.parse(token.text)

  if (token.access_token) {
    access_token = token.access_token
  }

  console.log(token, access_token)

  // 2、发送模板消息
  let res = await request
    .post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`)
    .send(requestData)
    .set('Accept', 'application/json')

  console.log(res.text)

  ctx.body = JSON.parse(res.text)
})

// response
// app.use(ctx => {
//   ctx.body = 'Hello Koa';
// });
app.use(bodyparser());
app.use(router.routes(), router.allowedMethods())

app.listen(11666);